<?php

namespace Parser\Separator;

use Parser\Enquiry;
use Parser\Parser;
use Parser\Repetition;

class PICCJS implements BaseSeparator
{
    public static $ApiKindList = [
        3000 => '051050', //车损
        4000 => '051051', //三者
        5002 => '051052', //司机
        5001 => '051053', //乘客
    ];

    public function interpreter(array $array, $parser)
    {
        if ($this->error($array, $parser)) {
            return;
        }

        $parser->result = $this->analysis($array);
    }

    /**
     *错误解析
     * Author:ls
     *
     * @param $array
     * @param $parser
     * @return bool
     */
    public function error(&$array, $parser): bool
    {
        if (!isset($array['data'][0])) {
            $parser->message = $array['msg'] ?? $array['errorMsg'] ?? '报价失败';
            $parser->code = '500';
            return true;
        }
        $array = $array['data'][0] ?? [];

        if ($errorMessage = $array['biInsuredemandVoList'][0]['ciInsureDemandDAA']['remark'] ?? false) {
            $parser->message = $errorMessage;
            $parser->code = '500';
            return true;
        }

        if (($errorTitle = $array['errorTitle'] ?? false) and ($errorMsg = $array['errorMsg'] ?? false)) {
            if (preg_match('/报价次数过于频繁/', $errorMsg)) {
                $errorMsg = '三代系统提示报价次数过于频繁,请稍后重试';
            }
            $parser->message = $errorMsg ?? $errorTitle;
            $parser->code = '500';
            return true;
        }
        if ($errorMessage = $array['errMessage'] ?? false and $errorMessage) {
            if (!preg_match('/此单符合续保条件，已按照续保流程处理，/', $errorMessage)) {
                $parser->message = $errorMessage;
                $parser->code = '500';
                return true;
            }
        }

        return false;
    }


    public function analysis($array): array
    {
        $enquiry = new enquiry();

        $enquiry->setTCIPremium((string)($array['ciInsureVOList'][0]['ciInsureDemand']['basePremium'] ?? '0'));
        $enquiry->setTCITotal((string)($array['ciInsureVOList'][0]['ciInsureDemand']['premium'] ?? '0'));
        $enquiry->setTaxTotal((string)($array['ciInsureVOList'][0]['ciInsureTax']['sumTax'] ?? '0'));
        $enquiry->setTaxPremium((string)($array['ciInsureVOList'][0]['ciInsureTax']['annualTaxDue'] ?? '0'));

        if (isset($array['biInsuredemandVoList'][0]['prpCitemKinds'])) {
            foreach ($array['biInsuredemandVoList'][0]['prpCitemKinds'] as $kindList) {
                $enquiry->setVCIDiscount((string)$kindList['disCount']);

                $enquiry->VCIPremiumAppend($kindList['benchMarkPremium'] ?? '0');

                $code = (string)array_search($kindList['kindCode'], self::$ApiKindList);
                if (!$code) {
                    continue;
                }
                $coverages['code'] = $code;
                $coverages['shortName'] = $kindList['kindName'] ?? '';
                $coverages['insuredDesc'] = (string)($kindList['amount'] ?? '');
                $coverages['total'] = (string)($kindList['premium'] ?? '0');

                $enquiry->VCITotalAppend($coverages['total']);
                $enquiry->setVCICoverages($coverages);
            }
        }
        //费率调整系数
        if ($factors = $array['biInsuredemandVoList'][0]['prpCprofitFactors'] ?? false) {
            foreach ($factors as $factor) {
                //自主定价系数
                if ($profitCode = $factor['id']['profitCode'] ?? '' and $profitCode == 'C10') {
                    $enquiry->setIndependentPriceRatio(bcdiv($factor['rate'] ?? '0', 100, 6));
                    break;
                }
                //无赔款优待优惠系数C01
                if ($profitCode = $factor['id']['profitCode'] ?? '' and $profitCode == 'C10') {
                    $enquiry->setNCDRate(bcdiv($factor['rate'] ?? '0', 100, 6));
                    break;
                }
            }
        }
        $enquiry->setTotal();

        if ($repeat = $array['prpReInsureItems'] ?? []) {
            $enquiry->failure();
            if (count($repeat) >= 1) {
                $enquiry->setErrorTip('商业险重复投保');
            }
        }
        $enquiry->success();

        return $enquiry->get();
    }

    //数据解析
    public function repetition($array): Repetition
    {
        $array = $array['data'][0];

        $repetition = new Repetition();

        $repetitionData = $array['biInsuredemandVoList'][0]['ciInsureDemandRepets'] ?? false;

        $coverage = [];

        foreach ($repetitionData as $key => $repetitionDatum) {
            if (!$key) {
                $repetition->setLastSignTime(date('Y-m-d H:i:s', ($repetitionDatum['billDate']['time'] ?? 0) / 1000));
                $repetition->setLastCompany($repetitionDatum['insurerCode'] ?? '');
                $repetition->setLastStartAt(date('Y-m-d H:i:s', ($repetitionDatum['startDate']['time'] ?? 0) / 1000));
                $repetition->setLastPolicy($repetitionDatum['policyNo'] ?? '');
                $repetition->setLastEndTime(date('Y-m-d H:i:s', ($repetitionDatum['endDate']['time'] ?? 0) / 1000));
                $repetition->setLicense($repetitionDatum['licenseNo'] ?? '');
            }

            if ($repetitionDatum['kindName'] ?? false) {
                $coverage[] = $repetitionDatum['kindName'];
            }
        }

        $repetition->setLastCoverage($coverage);

        if ($repetition->getLastCompany()) {
            $repetition->setStatus('success');
        }

        return $repetition;
    }
}

